import React, { useState, useEffect } from 'react';
import { Button, Divider, List, Pagination, Icon, Popconfirm, Input } from 'antd';
import { useHistory } from 'react-router-dom';
import RcViewer from '@hanyk/rc-viewer';
import {
  openNotification_util, fetchsync_util,
  convertISODateTimeToYYYYMMDDHHMM,
  use_olreport_bybbbm,
  getCurrentDate_util,
  usenowDate,
  convertISODateTimeToYYYYMMDD,
} from '../util/util.js'
import Customfielditem_hook_mobile from '../newmes/customfielditem_hook_mobile.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { SaveOutlined } from '@ant-design/icons';
import { use_qgd_mx_initformdata } from './use_mobile_config.js';
import { v4 as uuidv4 } from 'uuid';
moment.locale('zh-cn')
var storage = window.localStorage;
import mainpage_bg from '../../../img/shipSRM/mobile_top.png'

const TitleItem = (props) => {
  return <div style={{
    marginTop: "0.1rem", height: "1.2rem", fontSize: "0.75rem", position: "relative", width: "95vw", textIndent: "0.3rem", color: "black",
    backgroundColor: "white", lineHeight: "1.2rem", fontWeight: "800", textAlign: "left", borderLeftStyle: "solid", borderWidth: "0.3rem",
    borderColor: "#377af6", marginLeft: "0"
  }}>
    {props.title}
  </div>
}

const Normalitem = (props) => {
  var height = props.height
  return (
    <div style={{ textIndent:"0.4rem",width: "95%", marginLeft: "0%", height: height ? height : "1.2rem", position: "relative", fontWeight: "400" }}>
      <div style={styles.lineitemnormal}>
        <span style={props.styleobj}>
        &nbsp;{props.label}:&nbsp;</span><span style={props.styleobjright}>{props.value}</span></div>
    </div>)
}
const Normalitemtwo = (props) => {
  return (
    <div style={styles.listitemnormal}>
      <div style={styles.listitemleft}>
      &nbsp;  &nbsp;{props.label}:&nbsp;

        <span style={{ fontWeight: "800" }}>
          {props.value}</span></div>
      <div style={{ width: "50%", height: "100%", position: "absolute", right: "0", top: "0", textAlign: "left" }}>
        {props.labeltwo}:&nbsp;{props.valueTwo}&nbsp;</div>
    </div>

  )

}

const Mobile_qgd_form = () => {
  const history = useHistory();
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
    datas_wl: [],
  })
  //请购单明细
  const [mxdata, setmxdata] = useState([])
  const [nowData, setNowData] = useState([])
  const [delidarr, setDelidarr] = useState([]);
  const [current, setCurrent] = useState(1)
  const [pagesize, setPageSize] = useState(5)
  //表单数据
  const [formdata, setformdata] = useState(use_qgd_mx_initformdata)

  //初始化

  const deleteMx = (item) => {
    let newmxdata = mxdata.filter(item2 => item2.id != item.id).map((item3, index) => {
      item3.index = index
      return item3
    })
    delidarr.push(item.id)
    setDelidarr(delidarr)
    setmxdata(newmxdata)
    let nowData = newmxdata.slice((current - 1) * pagesize, current * pagesize)
    setNowData(nowData)
  }

  const clean = () => {
    for (var item in formdata) {
      formdata[item].inputType!=='none'?formdata[item].value = "":""
    }
    setformdata({ ...formdata })
  }

  // 页面进入加载数据
  useEffect(() => {
    JSON.parse(storage.preitem_qgd).type == "add" ? initdatasource() :
      JSON.parse(storage.preitem_qgd).type == "edit" ? init(JSON.parse(storage.preitem_qgd).data.id) : ""
  }, [])


  const handleInputChange = (value) => {
    formdata.bz.value = value
    setformdata({ ...formdata })
  }

  //初始化
  const init = async (id) => {
    let rtdata = await fetchsync_util("/admin/cggl/query_qgd_byid", 'POST', { id }, "json")

    let newformdata = formdata
    newformdata.djrq.value = convertISODateTimeToYYYYMMDD(rtdata.resultdata.formdata.djrq)
    newformdata.djh.value = rtdata.resultdata.formdata.djh
    newformdata.bz.value = rtdata.resultdata.formdata.bz
    newformdata.create_by.value = rtdata.resultdata.formdata.create_by
    setformdata({ ...newformdata })
    let mxdata = rtdata.resultdata.mxdata.map((item, index) => {
      item.djrq = item.djrq === null ? "" : convertISODateTimeToYYYYMMDDHHMM(item.djrq)
      return { ...item, index }
    })
    setmxdata(mxdata)
    initdatasource()
    let nowData = mxdata.slice((current - 1) * pagesize, current * pagesize)
    setNowData(nowData)
  }

  /**
  * 初始化数据仓库
  */
  const initdatasource = async () => {
    //在线报表
    var cusqueryobj = await use_olreport_bybbbm(['query_wl'])
    dynDatasObject.datas_wl = cusqueryobj.query_wl
    setdynDatasObject({ ...dynDatasObject })
  }


  //设置value
  const setfield = (onekey, value, settype) => {
    if (settype == 'single') {
      var newitem = formdata[onekey]
      newitem.value = value
      let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
      setformdata(newformdata)
    }
    else if (settype == "muti") {
      let [tansferarr, selectrow, newformdata] = [onekey, value, {}];
      tansferarr.forEach(item => {
        var newitem = formdata[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdata, { [item.target]: newitem });
      })
      setformdata(newformdata)
    }

  }

  const hanldeadd = async () => {
    var isExist = 0
    if (formdata.wlbm.value == "" || formdata.wlmc.value == "" || formdata.qgsl.value == "") {
      openNotification_util("请输入物料编码、物料名称和请购数量")
      return
    }
    mxdata.forEach(item => {
      if (item.wlbm == formdata.wlbm.value) {
        openNotification_util("该物料编码已存在，请合并请购")
        isExist = 1
        return
      }
    })
    if (isExist == 1) {
      return
    }
    let newmxdata = {}
    for (var item in formdata) {
      newmxdata[item] = formdata[item].value
    }
    newmxdata.index = mxdata.length
    newmxdata.id = uuidv4()
    mxdata.push(newmxdata)
    setmxdata(mxdata)
    let nowData = mxdata.slice((current - 1) * pagesize, current * pagesize)
    setNowData(nowData)
    clean()
  }

  const handleupload = async () => {
    // var checkobj = checkdatavalid_util_formdata(formdata)
    // //主表字段校验没通过不能保存，目前没写子表校验。
    // openNotification_util(checkobj.rtmessage);
    // if (!checkobj.rtstatus) { return; }
    // else;
    //设置submit url
    let rtdata
    if (JSON.parse(storage.preitem_qgd).type == "add") {
      rtdata = await fetchsync_util("/admin/cggl/add_qgd_mx", 'POST', { mxdata, formdata }, "json")

    } else {
      rtdata = await fetchsync_util("/admin/cggl/update_qgd_mx", 'POST', { mainid: JSON.parse(storage.preitem_qgd).data.id, mxdata, 
        delidarr,formdata}, "json")
    }
    openNotification_util(rtdata.rtmessage)
    history.push({ pathname: '/shipSRM_mobile/cggl/mobile_qgd_list' })
  }

  const onShowSizeChange = (page) => {
    let nowData = mxdata.slice((page - 1) * pagesize, page * pagesize)
    setNowData(nowData)
    setCurrent(page)
  }

  //登出
  const handlelogout = () => {
    storage.islogin = 'loginout'
    history.push({ pathname: '/mobile_login' });
  }

  //去首页
  const handletomainpage = () => {
    history.push({ pathname: '/shipSRM_mobile/mobile_mainpage' });
  }

  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook_mobile form={formdata} item={{ inputType: "none" }}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
        :
        <Customfielditem_hook_mobile form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype) }} />
      return rtitem
    }
    )
    return renderstr
  }

  return (

    <div style={{ height: "100vh", width: "100%", position: 'relative', backgroundColor: "white" }}>
      {/* 首页  */}
      <div style={{
        width: "100%", height: "38vw",
        backgroundImage: `url(${mainpage_bg})`,
        position: "relative", fontSize: "0.9rem",
        textIndent: "2rem", fontWeight: "500", color: "white", borderRadius: "0 0 15px 15px"
      }} >
        <br />&nbsp;&nbsp;&nbsp;&nbsp;请购单
        <Button type="primary" style={{ lineHeight: "18%", backgroundColor: "rgba(0,0,0,0.1)", height: "18%", position: "absolute", right: "35%", top: "5%", textAlign: "center" }}
          onClick={() => { history.push({ pathname: '/shipSRM_mobile/cggl/mobile_qgd_list' }) }}>返回列表
        </Button>
        <Button type="primary" style={{ lineHeight: "18%", backgroundColor: "rgba(0,0,0,0.1)", height: "18%", position: "absolute", right: "1%", top: "5%", textAlign: "center" }}
          onClick={handlelogout}>
          登出
        </Button>
        <Button type="primary" style={{ lineHeight: "18%", backgroundColor: "rgba(0,0,0,0.1)", height: "18%", position: "absolute", right: "18%", top: "5%", textAlign: "center" }}
          onClick={handletomainpage}>
          首页
        </Button>
      </div>

      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "0%", backgroundColor: "", display: "flex",
          textIndent: "0rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap",
        }}>
          <TitleItem title="表单信息" />
          {/* <Normalitem label="单据编号" value={formdata.djh.value} /> */}
          <Normalitemtwo label="请购人" value={formdata.create_by.value} labeltwo="请购日期" valueTwo={formdata.djrq.value} />
          <div style={{ width: "95%", marginLeft: "2%", height: "2rem", position: "relative", fontWeight: "800" }}>
            <div style={styles.lineitemnormal}>
              <span >&nbsp;&nbsp;请购说明&nbsp;:&nbsp;</span>
              <Input style={{width:'60vw',height:'2rem'}} value={formdata.bz.value} onChange={(e)=>{handleInputChange(e.target.value)}} />
            </div>
          </div>
          {renderfileditem()}
        </div>


        <div style={{ width: "100%", position: "relative", }} >

          <Button type="primary" onClick={() => { hanldeadd() }}
            style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.6rem", left: "1rem", position: "absolute" }}>
            <SaveOutlined />{"新增"}</Button>
        </div>
        {/* 主表区域结束 */}
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  

        <div style={{ ...styles.linestyle, marginTop: '5vw' }} >
          <div style={styles.lineleft}><a style={{ color: "red" }}></a>&nbsp;请购单明细</div>
        </div>

        <div style={{ width: "90vw", height: "", backgroundColor: "#FFFFFF", marginLeft: "5vw" }}>
          <List
            itemLayout="horizontal"
            dataSource={nowData}
            renderItem={(item, index) => (

              <div style={{
                width: "100%", backgroundColor: "white", marginTop: "5px", position: "relative",
                fontWeight: "400", fontSize: "0.6rem", borderRadius: "5px", overflow: "hidden", textAlign: 'left', lineHeight: "1.2rem",
                borderStyle: "solid", borderWidth: "0.05rem", borderColor: "#B8B8B8"
              }}>
                <div >
                  <RcViewer options={{ toolbar: 1 }} style={{ height: '20vw', position: 'absolute', right: "1vw", top: "1vw", zIndex: '100' }}>
                    <div key={index} style={{ width: "20vw", height: "20vw", position: 'absolute', right: "1vw", top: "1vw", marginLeft: "0.1vw", display: "inline-block" }}>
                      <img
                        style={{ width: "90%", left: "0", margin: "auto" }}
                        src={`http://111.77.154.58:2233/${item.wltp}`}
                        alt=""
                      />
                    </div>
                  </RcViewer>
                </div>
                <div style={{ width: "100%", height: "0.8rem", position: "relative", marginTop: "0.5rem" }}>
                  <div style={{
                    width: "90%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left", fontWeight: "600",
                    color: "#377AF6"
                  }}>
                    &nbsp;&nbsp;序号：{item.index + 1}</div>
                </div>
                {/* <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "90%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;检验编号：{JSON.parse(storage.preitem_qgd).data.jybh}</div>
                </div> */}

                <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "90%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;物料名称：{item.wlmc}</div>
                </div>
                <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "70%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;物料编码：{item.wlbm}&nbsp;&nbsp;</div>
                </div>
                {/* <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "70%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;原物料编码：{item.ywlbm}&nbsp;&nbsp;</div>
                </div> */}
                <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "70%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;规格型号：{item.ggxh}&nbsp;&nbsp;</div>
                </div>

                <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "50%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;单位：{item.dw}</div>
                  <div style={{ width: "50%", height: "100%", position: "absolute", right: "0", top: "0", textAlign: "left" }}>
                    请购数量：{item.qgsl}&nbsp;&nbsp;</div>
                </div>
                <div style={{ width: "100%", height: "0.8rem", position: "relative" }}>
                  <div style={{ width: "70%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" }}>
                    &nbsp;&nbsp;备注说明：{item.bzsm}&nbsp;&nbsp;</div>
                </div>
                <div style={{
                  width: "100%", backgroundColor: "white", fontWeight: "400", lineHeight: "0.8rem",
                  wordWrap: "break-word", textIndent: "0", margin: "5px",
                }}>
                  <Popconfirm
                    title="删除"
                    description="是否确实删除此检验?"
                    onConfirm={() => deleteMx(item)}
                    okText="删除"
                    cancelText="取消"
                  >
                    <Button
                      type="primary" style={{ height: "1.2rem", fontSize: "0.55rem", position: "relative" }}>删除</Button>
                  </Popconfirm>
                </div>
              </div>
            )}
          />
          <div style={{ height: "0.2rem" }}></div>
          <Pagination defaultCurrent={1} size="small" total={mxdata.length}
            onChange={onShowSizeChange} current={current} pageSize={pagesize}
          />
        </div>
        <br />
        <div style={{ ...styles.linestyle, marginTop: '2vw' }}>
          <Button type="" style={{
            width: "90%", height: "1.8rem", backgroundColor: "#377AF6", color: "rgb(254,209,0)",
            fontSize: "0.8rem", borderRadius: "0.3rem", margin: '1vh auto'
          }} onClick={handleupload}>  <Icon type="file-add" /> 提交 </Button >
        </div>

      </div>
    </div>
  )
}


export default Mobile_qgd_form

var styles = {
  kshcontainer: {
    width: "100%", height: "90%", position: "absolute", top: "12vh", left: "0vw", backgroundColor: "white", color: "black",
    borderRadius: "10px",
  },
  lineitemnormal: { width: "100%", height: "100%", position: "absolute", left: "0", top: "0", textAlign: "left" },
  listitemnormal: { width: "100%", height: "1.2rem", position: "relative", fontWeight: "800" },
  linestyle: { height: "1.8rem", fontSize: "0.7rem", position: "relative", width: "100%", textIndent: "1rem" },
  listitemleft: { width: "50%", height: "100%", position: "absolute", left: "2%", top: "0", textAlign: "left" },
  lineleft: { width: "100%", height: "100%", position: "absolute", left: "0%", textAlign: "left", lineHeight: "2rem", fontSize: "0.75rem", fontWeight: "700" },
}

